home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 19 / CU Amiga Magazine's Super CD-ROM 19 (1998)(EMAP Images)(GB)[!][issue 1998-02].iso / CUCD / Programming / LEDA / source / src / graph_alg / _all_pairs.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-16  |  2.0 KB  |  75 lines

  1. /*******************************************************************************
  2. +
  3. +  LEDA  3.1c
  4. +
  5. +
  6. +  _all_pairs.c
  7. +
  8. +
  9. +  Copyright (c) 1994  by  Max-Planck-Institut fuer Informatik
  10. +  Im Stadtwald, 6600 Saarbruecken, FRG     
  11. +  All rights reserved.
  12. *******************************************************************************/
  13.  
  14.  
  15.  
  16. /*******************************************************************************
  17. *                                                                              *
  18. *  ALL PAIRS SHORTEST PATHS                                                    *
  19. *                                                                              *
  20. *******************************************************************************/
  21.  
  22. #include <LEDA/graph_alg.h>
  23.  
  24. bool ALL_PAIRS_SHORTEST_PATHS(graph&G, const edge_array<num_type>& cost, 
  25.                                              node_matrix<num_type>& DIST)
  26.   // computes for every node pair (v,w) DIST(v,w) = cost of the least cost
  27.   // path from v to w, the single source shortest paths algorithms BELLMAN_FORD
  28.   // and DIJKSTRA are used as subroutines. Returns false if there is a
  29.   // negative cost circle and true otherwise.
  30.  
  31.   edge e;
  32.   node v,w;
  33.  
  34.   num_type C = 0;
  35.   forall_edges(e,G)  C += ((cost[e]>0) ? cost[e] : -cost[e]);
  36.  
  37.   node s = G.new_node();
  38.   forall_nodes(v,G) G.new_edge(s,v);
  39.  
  40.   edge_array<num_type> cost1(G);
  41.   node_array<num_type> dist1(G);
  42.  
  43.   node_array<edge>  pred(G);
  44.  
  45.   forall_edges(e,G)  
  46.     if (source(e)==s) cost1[e] = C;
  47.     else cost1[e] =  cost[e];
  48.  
  49.   if (!BELLMAN_FORD(G,s,cost1,dist1,pred)) return false;
  50.  
  51.   G.del_node(s);
  52.  
  53.   forall_edges(e,G) cost1[e] = dist1[source(e)] + cost[e] - dist1[target(e)];
  54.  
  55.  
  56.   // (G,cost1) is a non-negative network
  57.   // for every node v compute row DIST[v] of the distance matrix  DIST 
  58.   // by a call of DIJKSTRA(G,v,cost1,DIST[v])
  59.  
  60.   forall_nodes(v,G) DIJKSTRA(G,v,cost1,DIST[v],pred);
  61.  
  62.  
  63.   // correct the entries of DIST
  64.  
  65.   forall_nodes(v,G)
  66.   { num_type dv = dist1[v];
  67.     forall_nodes(w,G) DIST(v,w) += (dist1[w] - dv);
  68.    }
  69.  
  70.  return true;
  71. }
  72.  
  73.